// 导入pinia的状态管理
import { defineStore } from "pinia";
// 导入的token的一套 存储token 删除token 检查token
import { getToken, removeToken, setToken } from "../utils/token-utils";
// 判断用户权限的
import type { UserInfoState } from "./interface";
// 导入element组件
import { ElMessage } from "element-plus";
// 导入router组件
import { staticRoutes } from "@/router/routes";
// 引入登录接口文件
import { reqUserLogin, reqLogout, reqUserInfo } from "@/api/user/index";
// 导入类型
import type { LoginResponseData, UserInfo } from "@/api/user/type/index";

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  // 设置初始化
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: "",
    avatar: "",
    menuRoutes: [],
  }),
  // 修改
  actions: {
    async login(username: string, password: string) {
      const result: LoginResponseData = await reqUserLogin({
        username,
        password,
      });
      // 本地存储持久化存储
      setToken(result.token);
      // pinia仓库token
      this.token = result.token;
    },
    // 登录成功返回的
    async getInfo() {
      // 发送请求
      let result: UserInfo = await reqUserInfo();
      // 存储用户的信息
      this.name = result.name;
      this.avatar = result.avatar;
      this.menuRoutes = staticRoutes;
    },

    async reset() {
      // 退出登录的请求
      await reqLogout();
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.name = "";
      this.avatar = "";
    },
  },
});
